﻿using Microsoft.AspNetCore.Mvc;
using Simple.Services.System.Jobs;
using Microsoft.Extensions.DependencyInjection;
using System;
using Simple.Services.System;

[Route("[controller]")]
[ApiController]
public class TimerController : ControllerBase
{
    private readonly TimerTaskService _timerTask;

    public TimerController(TimerTaskService timerTask)
    {
        _timerTask = timerTask;
        _timerTask.Initialize(15000, async () =>
        {
            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                var dangerMsg = await _timerTask.GetDangerAsync(cancellationTokenSource.Token);
                var violationMsg = await _timerTask.GetViolationAsync(cancellationTokenSource.Token);
                // 处理获取到的danger消息
                if(dangerMsg!= null)
                {
                    utilService.PushDanger(dangerMsg);
                }
                if (violationMsg != null)
                {
                    utilService.PushDanger(violationMsg);
                }

            }
        });
    }

    // GET: timer/start
    [HttpGet("start")]
    public IActionResult StartTimer()
    {
        try
        {
            _timerTask.Start();
            return Ok("Timer started.");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error starting timer: {ex.Message}");
        }
    }

    // GET: timer/stop
    [HttpGet("stop")]
    public IActionResult StopTimer()
    {
        try
        {
            _timerTask.Stop();
            return Ok("Timer stopped.");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error stopping timer: {ex.Message}");
        }
    }
    // GET: timer/status
    [HttpGet("status")]
    public IActionResult GetTimerStatus()
    {
        try
        {
            var isRunning = _timerTask.IsRunning();
            return Ok(new { isRunning });
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error retrieving timer status: {ex.Message}");
        }
    }
}
